<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>授权资源管理</title>
        <% include("/common/common_css_js.html"){} %>
    </head>
    <body>

        <div style="padding-bottom: 5px;">
            <div id="queryForm" class="uc-toolbaroverflow" _borderStyle="border-top:0;">
                <span>资源名称：</span>
                <input id="keyName" name="keyName" class="mini-textbox" style="width:250px" emptyText="资源名称" required="false" requiredErrorText="资源名称不能为空"/>
                <span>资源类型：</span>
                <input id="keyResourceTypeId" name="keyResourceTypeId" class="mini-combobox" style="width: 250px;" textField="name" valueField="id" emptyText="请选择..."
                       required="false" allowInput="false" showNullItem="true" nullItemText="请选择..." />

                <div style="margin-top: 5px"></div>
                <a class="mini-button" iconCls="icon-search" onclick="search()">查询</a>
                <a class="mini-button" iconCls="icon-new" onclick="clearSearch()">清空查询条件</a>

                <span class="separator"></span>
                <a class="mini-button" iconCls="icon-add" onclick="showAddResource()">新增</a>
                <a class="mini-button" iconCls="icon-edit" onclick="showEditResource()">编辑</a>

                <span class="separator"></span>
                <a class="mini-button" iconCls="icon-add" onclick="showAddMenuResource()">添加菜单资源</a>

            </div>
        </div>

        <!--

        create table sys_permission
(
	id varchar(20) not null comment '系统授权许可表ID'
		primary key,
	pid varchar(20) null comment '父ID',
	pids varchar(2000) null comment '当前结点所有父结点ID,各ID用半角逗号分隔',
	name varchar(100) not null comment '资源名称',
	resource_type_id bigint not null comment '资源类型ID，关联xt_dic.id key=''XT_DIC_PERMISSION_TYPE''',
	url varchar(1000) null comment '资源访问URL',
	permission_code varchar(20) not null comment '权限编码,用户自定义，不可重复',
	constraint sys_permission_permission_code_uindex
		unique (permission_code)
)
comment '系统授权许可表';

        -->

        <div class = "mini-fit">
            <div id="datagrid1" class="mini-datagrid"
                 style="width: 100%; height: 100%;"
                 url="${base}/pages/system_maintain/permission/query" idField="id"
                 showPager="true" pageSize="20" sizeList="[10,20,30,50,100]"
                 allowResize="true"
                 allowCellWrap="true"
                 multiSelect = "true"
                 sortField="menuId"
                 sortOrder="asc"
            >
                <div property="columns">
                    <div type="checkcolumn" ></div>
                    <div field="id" width="140" headerAlign="center" align="center" allowSort="true">资源ID</div>
                    <div field="pid" width="140" headerAlign="center" align="center" allowSort="true">资源PID</div>
                    <div field="pids" width="140" headerAlign="center" align="center" allowSort="true">资源PIDS</div>
                    <div field="name" width="140" headerAlign="center" align="center" allowSort="true">资源名称</div>
                    <div field="resourceTypeId" width="140" headerAlign="center" align="center" allowSort="true" data-options='{cacheName:"sysDic"}' renderer="commonRender">资源类型</div>
                    <div field="url" width="140" headerAlign="center" align="center">URL</div>
                    <div field="permissionCode" width="140" headerAlign="center" align="center">授权编码</div>
                    <div field="menuName" width="140" headerAlign="center" align="center" allowSort="true">归属模块</div>

                </div>
            </div>
        </div>


        <!-- 非菜单授权资源添加面板 -->
        <div id="resourcePanel" class="mini-window" title="授权资源" style="width:800px;height:500px;"
             showMaxButton="true" showCollapseButton="false" showMinButton="true" showShadow="true"
             showToolbar="true" showFooter="true" showModal="true" allowResize="true" allowDrag="true">

            <div property="footer" style="padding:10px;text-align: right">
                <a  class="mini-button" iconCls="icon-ok" onclick="save()">保存</a>
                <a  class="mini-button" iconCls="icon-close" onclick="closePanel('resourcePanel')">关闭</a>
            </div>

            <div id="resourceForm" style="padding: 5px">
                <span>资源类型:</span>
                <input id="resourceTypeId" name="resourceTypeId" class="mini-combobox" style="width: 100px;" textField="name" valueField="id" emptyText="请选择..."
                       required="true" allowInput="false" showNullItem="true" nullItemText="请选择..."  />

                <span>模块选择:</span>
                <input id="menuId" name="menuId" class="mini-treeselect" style="width:200px;" textField="name" valueField="id" emptyText="请选择..."
                       required="true" allowInput="false" showNullItem="true" nullItemText="请选择..."
                       requiredErrorText="资源模块不能为空"   virtualScroll="true"
                       onvaluechanged="menuNodeSelect"/>
                <input id="menuName" name="menuName" class="mini-hidden" emptyText="菜单名称" required="true" requiredErrorText="菜单名称不能为空"/>

                <div style="margin-top: 5px"></div>
                <span>资源名称:</span>
                <input id="name" name="name" class="mini-textbox" style="width: 200px" emptyText="资源名称" required="true" requiredErrorText="资源名称不能为空"/>

                <span>权限编码:</span>
                <input id="permissionCode" name="permissionCode" class="mini-textbox" style="width: 200px" emptyText="权限编码" required="true" requiredErrorText="权限编码不能为空"/>

                <a class="mini-button" iconCls="icon-add" onclick="addPermissionToGrid()">添加</a>
                <a class="mini-button" iconCls="icon-remove" onclick="removePermissionFromGrid()">移除</a>

                <div style="margin-top: 5px"></div>
                <div id="permissionDatagrid" class="mini-datagrid"
                     style="width: 100%; height: 300px;"
                     idField="id"
                     showPager="false"
                     multiSelect = "true" allowResize="false">
                    <div property="columns">
                        <div type="checkcolumn" ></div>
                        <div field="name" width="140" headerAlign="center" align="center" allowSort="true">资源名称</div>
                        <div field="resourceTypeId" width="140" headerAlign="center" align="center" allowSort="true" data-options='{cacheName:"sysDic"}' renderer="commonRender">资源类型</div>
                        <div field="permissionCode" width="140" headerAlign="center" align="center" allowSort="true" >权限编码</div>
                        <div field="menuName" width="140" headerAlign="center" align="center" allowSort="true" >归属模块</div>
                    </div>
                </div>


            </div>
        </div>


        <script type="text/javascript">
            mini.parse();

            let keyName = mini.get("keyName");
            let keyResourceTypeId = mini.get("keyResourceTypeId");
            let resourceTypeId = mini.get("resourceTypeId");

            let grid = mini.get("datagrid1");

            let opFlag = mini.get("opFlag");

            let resourceForm = new mini.Form("#resourceForm");

            let menuId = mini.get("menuId");
            let menuName = mini.get("menuName");
            let name = mini.get("name");
            let permissionCode = mini.get("permissionCode");

            let permissionDatagrid = mini.get("permissionDatagrid");

            /**
             * MEMU(601, "菜单", "菜单"),
             * BUTTON(602, "按钮", "按钮");
             */
            let resourceType = {menu:601,button:602};

            $(function () {
                // 授权资源类型
                let keyResourceTypeIdJsonData = commonRenderSysDicDropListByKey("sysDic","XT_DIC_PERMISSION_TYPE");
                keyResourceTypeId.load(keyResourceTypeIdJsonData);
                resourceTypeId.load(public_deepClone(keyResourceTypeIdJsonData));

                // 加载列表数据
                reloadMenu();

                // 加载列表数据
                grid.load();

            });

            function reloadMenu(){
                menuData = public_getServerData("${base}/menu/getMenuNoPageList",{pid:"0"});
                menuId.loadList(menuData,"id","pid");
            }


            function search() {
                let form = new mini.Form("#queryForm");
                let data = form.getData(true);
                grid.load(data);
            }

            function clearSearch() {
                let form = new mini.Form("#queryForm");
                form.clear();
            }

            /**
             * 面板关闭
             * @param winId
             */
            function closePanel(winId) {
                public_onCancel(winId);
            }

            /**
             * 调用刷新菜单资源,因为菜单资源是固定的，所以不建议使用选择，而且菜单资源是必须每一项都要添加，所以直接添加
             */
            function showAddMenuResource(opFlagValue) {
                mini.confirm("确定刷新授权菜单资源？", "菜单授权资源提示",
                    function(action) {
                        if (action == "ok") {
                            let ret = public_getServerData("${base}/pages/system_maintain/permission/refreshAuthMenuResource");
                            showAlert(ret.message,function (){
                                if(ret.ok){
                                    // 重新刷新数据
                                    grid.reload();
                                }
                            });
                        }
                    });
            }


            /**
             * 资源添加
             * @param opType
             */
            function showAddResource() {
                // 清空表单
                resourceForm.clear();

                // 重新设置数据
                resourceTypeId.setValue(resourceType.button);
                resourceTypeId.setEnabled(false);
                menuId.setEnabled(true);

                // 清空数据
                permissionArray.splice(0,permissionArray.length);
                // 重新绑定
                reBindDatagrid();

                // 显示面板
                public_showModelAtPos("resourcePanel", "center", "middle");
            }

            /**
             * 资源编辑
             * @param opType
             */
            function showEditResource() {
                let selectItems = grid.getSelecteds();
                if(selectItems.length == 0){
                    showAlert("请选择要编辑的授权资源对象!");
                    return;
                }
                if(selectItems.length>1){
                    showAlert("请选择一个授权资源对象!");
                    return;
                }

                let resourceObj = selectItems[0];
                if(resourceObj.resourceTypeId == resourceType.menu){
                    showAlert("菜单授权资源不提供编辑功能!");
                    return;
                }
                resourceForm.clear();
                resourceForm.setData(resourceObj);

                resourceTypeId.setEnabled(false);
                menuId.setEnabled(false);

                name.setValue("");
                permissionCode.setValue("");

                // 加载数据
                loadPermissionResource(resourceTypeId.getValue(),menuId.getValue());

                public_showModelAtPos("resourcePanel", "center", "middle");
            }


            let permissionArray = [];
            /**
             * 加载授权资源,根据资源类型，及其选择的模块ID
             */
            function loadPermissionResource(resourceTypeIdValue,menuIdValue) {

                permissionArray.splice(0,permissionArray.length);

                permissionArray = public_getServerData("${base}/pages/system_maintain/permission/queryNoPage?keyResourceTypeId="+ resourceTypeIdValue + "&keyMenuId=" +menuIdValue);

                // 重新绑定列表
                reBindDatagrid();
            }

            function reBindDatagrid() {
                // 清空
                permissionDatagrid.clearRows();

                // 开始渲染grid
                for(let obj of permissionArray){
                    permissionDatagrid.addRow(obj);
                }
            }

            /**
             * 添加权限
             */
            function addPermissionToGrid() {
                // 注意添加之前要检测否在permissionArray中存在
                // 构建对象
                let menuIdValue = menuId.getValue();
                let menuNameValue = menuName.getValue();
                let resourceTypeIdValue = resourceTypeId.getValue();
                let nameValue = name.getValue().trim();
                let permissionCodeValue = permissionCode.getValue().trim();

                if(public_isEmpty(menuIdValue)){
                    showAlert("没有选择资源对象模块!");
                    return;
                }

                let permissionObj={resourceTypeId:resourceTypeIdValue,name:nameValue,permissionCode:permissionCodeValue,menuId:menuIdValue,menuName:menuNameValue};

                let flag = false;
                for(let obj of permissionArray){
                    if(obj.name == permissionObj.name){
                        flag = true;
                        break;
                    }
                }

                if(flag){
                    showAlert("添加的资源名称在列表中已经存在，请修改资源名称!");
                    return;
                }

                for(let obj of permissionArray){
                    if(obj.resourceTypeId == permissionObj.resourceTypeId && obj.permissionCode == permissionObj.permissionCode && obj.menuId == permissionObj.menuId){
                        flag = true;
                        break;
                    }
                }

                if(flag){
                    showAlert("添加的资源在列表中已经存在，不能重复添加");
                    return;
                }


                permissionArray.push(permissionObj);
                // 重新绑定列表
                reBindDatagrid();

            }

            /**
             * 移除权限
             */
            function removePermissionFromGrid() {
                let selectedItems = permissionDatagrid.getSelecteds();

                if(selectedItems.length>0){
                    let tempArray = [];
                    for(let obj of permissionArray){
                        let flag=true;
                        for(let item of selectedItems){
                            if(obj.resourceTypeId == item.resourceTypeId && obj.name == item.name && obj.permissionCode == item.permissionCode && obj.menuId == item.menuId){
                                flag = false;
                                break;
                            }
                        }
                        if(flag){
                            tempArray.push(obj);
                        }
                    }

                    permissionArray.splice(0,permissionArray.length);

                    permissionArray.push(...tempArray);

                    reBindDatagrid();
                }
                else{
                    showAlert("没有选择需要移除的授权资源对象!");
                }
            }

            /**
             * 菜单节点被选择
             */
            function menuNodeSelect(e){

                let selectNodeValue = e.value;
                menuName.setValue(menuId.getText());

                let resourceTypeIdValue = resourceTypeId.getValue();

                // 加载现有的授权资源
                loadPermissionResource(resourceTypeIdValue,selectNodeValue);

            }


            /**
             * 保存操作
             */
            function save() {
                if(permissionArray.length==0){
                    showAlert("保存的授权资源列表为空，不能进行保存操作!");
                    return;
                }

                // 检验列表中的 MenuId 是否相同
                let menuId = permissionArray[0].menuId;
                let resourceTypeId = permissionArray[0].resourceTypeId;
                let flag = false;
                for(let obj of permissionArray){
                    if(obj.menuId != menuId || obj.resourceTypeId != resourceTypeId){
                        flag = true;
                        break;
                    }
                }

                if(flag){
                    showAlert("资源列表中有相同的授权码或授权资源类型不致，不能添加!");
                    return;
                }

                mini.confirm("确定保存授权资源", "保存提示",
                    function(action) {
                        if (action == "ok") {
                            let ret = public_getServerData("${base}/pages/system_maintain/permission/save",permissionArray);
                            showAlert(ret.message,function (){
                                if(ret.ok){
                                    // 重新刷新数据
                                    grid.reload();
                                    // 清空form
                                    resourceForm.clear();
                                    // 清空授权资源
                                    permissionArray.splice(0,permissionArray.length);
                                    // 关闭面板
                                    closePanel('resourcePanel');
                                }
                            });
                        }
                });
            }


        </script>


    </body>
</html>